package com.mjx.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mjx.Util.BeanFactory;
import com.mjx.Util.JSONFactory;
import com.mjx.entity.User;
import com.mjx.service.ChatService;
import com.mjx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by meijingxiang on 2017/3/14.
 */
@Controller
public class ChatController {

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    UserService userService;

    @Autowired
    ChatService chatService;

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public void login(@RequestParam String name, HttpServletRequest request, HttpServletResponse response) throws IOException {

        User user = chatService.login(name, request);
        response.sendRedirect("/index.jsp?uid=" + user.getId());
    }

    @ResponseBody
    @RequestMapping(value = "ip/check", method = RequestMethod.GET)
    public JSON ipCheck(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //将application保存，供scoket使用
        if (BeanFactory.getApplicationContext() == null)
            BeanFactory.setApplicationContext(applicationContext);
        User user = chatService.checkIpExists(request);
        JSONObject jsonObject = JSONFactory.getSuccessJSON();
        if (user != null){
            jsonObject.put("uid", user.getId());
        }
        return jsonObject;
    }
}
